<script setup lang="ts">
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import { useTenantSystemStore, useMemberStore } from '@/stores'
import { createDefaultToken } from './services/system'
import { postUIdLoginAPI } from './services/login'
import { convertUrlParams } from '@/utils/index'
import { pages } from '@/pages.json'

onLaunch(() => {

  const store = useTenantSystemStore()
  const memberStore = useMemberStore()
  let pid = 0
  let urlParams = []
  // #ifdef MP-WEIXIN
  pid = 480306
  // #endif
  // #ifdef H5
  pid = Number(window.location.href.replace(window.location.origin, '').split('/')[1])
  urlParams = convertUrlParams()
  // 从url解析邀请人id
  const inviter = urlParams.find(p => p.key == 'inviter')
  if (inviter && inviter.value) {
    memberStore.setInviter(inviter.value)
  }
  // #endif

  // 设置默认租户id
  store.setPId(isNaN(pid) ? 480306 : pid)

  // 从url 解析用户Id, 如果解析到则直接登录获取token
  const uid = urlParams.find(p => p.key == 'uid')
  if (uid && uid.value) {
    postUIdLoginAPI(uid.value).then((data) => {
      memberStore.setProfile(data)
      redirectTo()
    }).catch(() => { })

  } else {
    if (!store.state.defaultToken) {
      // 否则就是默认的租户token
      createDefaultToken(store.state.pid).then(data => {
        store.setToken(data)
        redirectTo()
      }).catch(() => { })
    }
  }

})
onShow(() => {

})
onHide(() => {

})

const redirectTo = () => {
  // #ifdef H5
  let hash = window.location.hash
  if (hash == '#/wechat_redirect') {
    hash = '#/'
  }
  let startPage = hash.replace('#', '')
  if (startPage == '/') {
    uni.switchTab({ url: '/pages/index/start' })
  } else {
    uni.reLaunch({ url: startPage })
  }
  // #endif

}
</script>

<style lang="scss">
// 字体图标
@import '@/styles/fonts.scss';
@import '@/styles/iconfont.css';
@import "@/styles/aj_custom/index.scss";

view,
navigator,
input,
scroll-view {
  box-sizing: border-box;
}

page {
  // background: url(static/images/login-bg.png) no-repeat;
  background-position: top;
  background-attachment: fixed;
  background-size: 100% 45%;
  background-color: #f5f5ff;
}

button::after {
  border: none;
}

swiper,
scroll-view {
  flex: 1;
  height: 100%;
  overflow: hidden;
}

image {
  width: 100%;
  height: 100%;
  vertical-align: middle;
}

// 两行省略
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
</style>
